package com.fc.entities

import javax.persistence.CascadeType
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.FetchType
import javax.persistence.JoinColumn
import javax.persistence.JoinTable
import javax.persistence.ManyToOne
import javax.persistence.OneToMany
import javax.persistence.Table
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;


@Entity
@Table(name = "Workout")
class Workout extends BaseEntity {
	@Column(name = "name")
	@NotNull
	@Size(min=3, max=64)
	String name

	@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
	@Fetch(FetchMode.SUBSELECT)
	@JoinTable(name = "Workout_WorkoutEntries", joinColumns = [ @JoinColumn(name = "workout_id", referencedColumnName="id") ], inverseJoinColumns = [ @JoinColumn(name = "workoutEntry_id", referencedColumnName="id") ])
	List<WorkoutEntry> workoutEntries = new ArrayList<WorkoutEntry>()
		
	@ManyToOne
	@NotNull
	User user
	
	
	private transient int entriesCount;
	
	int getEntriesCount() {
		return workoutEntries.size()
	}

	int getSumBurntCalories() {
		def sum = 0
		for (entry in workoutEntries) {
			sum += (entry.activity.burntCalories * (entry.minutes / entry.activity.minutes))
		}
		return sum?:0
	}

	int getSumMinutes() {
		def sum = workoutEntries.sum() { it.minutes }
		return sum?:0
	}
	
	@Override
	String toString() {
		name
	}
}
